import * as global from '../status.js';

const {
  extractNewUrls,
  // 菜单id常量对象
  contextMenusId,
  // 消息id常量对象
  messageId
} = global;

// ============> utils 
// 生成id随机数0 - 999
function getRandomId(){
  return Math.floor(Math.random()*1000);
}


// 插件初始化 / 更新周期
chrome.runtime.onInstalled.addListener(async (info) => {
  if (info.reason === 'install') {
    await chrome.storage.local.set(global);
  }
  if (info.reason === 'install' || info.reason === 'update'){
    // 创建新闻详情页的取证检测菜单
    await chrome.contextMenus.create({
      id: contextMenusId.NEWDETAIL,
      title: '内容采集',
      contexts: ['all'],
      documentUrlPatterns: extractNewUrls
    });
  }
});

// 监听菜单点击
chrome.contextMenus.onClicked.addListener(async (info, tab) => {
  // console.log(info);
  // console.log(tab);
  let xiaohongshuReg = /^https:\/\/www\.xiaohongshu\.com\/explore\/.+/;
  // 菜单点击 - 新闻详情页检测(非小红书)
  if (info.menuItemId === contextMenusId.NEWDETAIL && !xiaohongshuReg.test(tab.url)){
    const [ tab ] = await chrome.tabs.query({ active: true, lastFocusedWindow: true});
    console.log(tab)
    chrome.storage.local.get(`${tab.url}`)
      .then(async (res) => {
        console.log(res);
        if (!res[tab.url]){
          const datas = await chrome.tabs.sendMessage(tab.id, {
            id: messageId.NEWDETAIL
          });
          let datasMessage = datas ? '获取新闻信息成功!' : '获取新闻信息失败';
          let datasTitle = datas ? '操作成功' : '操作失败'; 
          chrome.notifications.create(`getnewsdatas${getRandomId()}`, {
            title: datasTitle,
            type: 'basic',
            message: datasMessage,
            iconUrl: '../icons/128.png'
          });
          if (datas){
            console.log('持久化tab信息');
            console.log(tab)
            console.log(datas);
            // 获取到脚本页返回的消息 - 持久化tab页面信息供popup使用
            await chrome.storage.local.set({
              [tab.url]: {
                favIconUrl: tab.favIconUrl,
                tabId: tab.id,
                url: tab.url,
                title: tab.title,
                datas
              }
            });
          }
        } else {
          chrome.notifications.create(`getnewsdatas${getRandomId()}`, {
            title: '警告',
            type: 'basic',
            message: '当前新闻已收集完毕，请查看弹窗处理结果',
            iconUrl: '../icons/128.png'
          });
        }
      })
  } else {

  }
});